<%@ page import="admin.Course" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="admin.Connectmysql" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %><%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2025/6/18
  Time: 20:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%!
    String escapeJson(String value) {
        if (value == null) return "";
        return value.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
%>
<%
    List<Course> courses = new ArrayList<>();
    Connectmysql cmysql = new Connectmysql(
            "jdbc:mysql://localhost:3306/exam1",
            "root",
            "root",
            "com.mysql.cj.jdbc.Driver");
    try {
        if(cmysql.open()){

            ResultSet rst= cmysql.executeSql(
                    "SELECT * FROM course;",
                    new Object[]{}
            );
            while (rst.next()) {
                Course course = new Course(
                        rst.getString("course_id"),
                        rst.getString("course_name"),
                        rst.getString("description"),
                        rst.getString("create_time"),
                        rst.getString("credit"),
                        rst.getString("course_teacher")
                );
                courses.add(course);
            }
            //Gson gson = new Gson();
            StringBuilder json = new StringBuilder("[");

            for (int i = 0; i < courses.size(); i++) {
                Course course = courses.get(i);

                json.append("{");
                json.append("\"course_id\":\"").append(escapeJson(course.getId())).append("\",");
                json.append("\"course_name\":\"").append(escapeJson(course.getName())).append("\",");
                json.append("\"description\":\"").append(escapeJson(course.getDescription())).append("\",");
                json.append("\"create_time\":\"").append(escapeJson(course.getCreateTime())).append("\",");
                json.append("\"course_teacher\":\"").append(escapeJson(course.getTeacher())).append("\"");
                json.append("}");

                if (i < courses.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");
            // 输出JSON
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json.toString());
            rst.close();
        }
    } catch (ClassNotFoundException f) {
        f.printStackTrace();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }

%>
